package com.hanyxx.thread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author layman
 * @date 2021/2/9
 */
public class Demo06 {
    public static void main(String[] args) {
        Demo06Service service = new Demo06Service(true);
        int size = 20;
        Demo06Thread[] threads = new Demo06Thread[size];
        for (int i = 0; i < size; i++) {
            threads[i] = new Demo06Thread(service);
        }
        for (int i = 0; i < size; i++) {
            threads[i].start();
        }
    }
}
class Demo06Service{
    private Lock lock;
    public Demo06Service(boolean isFair){
        //true的ReentrantLock是公平锁，反之为非公平锁
        this.lock = new ReentrantLock(isFair);
    }
    public void doSomething(){
        lock.lock();
        System.out.println(Thread.currentThread().getName()+" 被锁定了");
        lock.unlock();
    }
}
class Demo06Thread extends Thread{
    private Demo06Service service;
    public Demo06Thread(Demo06Service service){
        this.service = service;
    }
    @Override
    public void run() {
        service.doSomething();
    }
}
